# 后台任务：可以将这些操作放在后台执行，而不会阻塞主线程，从而提高应用的响应速度。
# 发邮件发短信之类的 如果不放到专门的任务队列中, 也不 MQ 消息
import time
from typing import Annotated
from fastapi import BackgroundTasks, Depends, FastAPI

app = FastAPI()


def write_log(message: str):
    with open("log.txt", mode="a") as log:
        log.write(message)


def get_query(background_tasks: BackgroundTasks, q: str | None = None):
    if q:
        message = f"found query: {q}\n"
        background_tasks.add_task(write_log, message)
    return q


@app.post("/send-notification/{email}")
async def send_notification(
        email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
    message = f"message to {email}\n"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent"}


# 模拟发送短信的函数
def send_sms(phone_number: str, message: str):
    # 模拟发送短信的延迟
    time.sleep(5)  # 假设发送短信需要一些时间
    print(f"Sent message to {phone_number}: {message}")


@app.post("/send-sms/")
async def send_sms_endpoint(phone_number: str, message: str, background_tasks: BackgroundTasks):
    # 将发送短信的任务添加到后台
    background_tasks.add_task(send_sms, phone_number, message)
    return {"message": "SMS is being sent in the background"}
